<!--已有规则目录树，用于选择管理规则  关联已有字段，表字段目录树-->
<template>
    <lay-card>
      <lay-row space="5" v-if="!showCheckbox">
        <lay-col md="22"></lay-col>
        <lay-col md="2">
          <lay-icon type="layui-icon-close" @click="cancelSubmit"></lay-icon>
        </lay-col>
      </lay-row>
      <lay-row space="10">
        <lay-tab v-model="dependType">
          <lay-tab-item title="规则" id="rule">
            <lay-input
                v-model="ruleName"
                :allow-clear="true"
                @clear="clearAndGetRules"
                size="sm"
                placeholder="请输入查询，区分大小写"
                @change="queryTargetRules"
                style="width: 80%"
            >
              <template #suffix>
                <lay-icon type="layui-icon-search" @click="queryTargetRules" size="sm"></lay-icon>
              </template>
            </lay-input>
            <lay-scroll :height="'240px'" style="width: 350px">
              <lay-tree
                  :data="rules"
                  :checkStrictly="true"
                  :showCheckbox="showCheckbox"
                  v-model:checkedKeys="checkedKeys"
                  @node-click="getRuleDetail"
              >
              </lay-tree>
            </lay-scroll>
          </lay-tab-item>
          <lay-tab-item title="表字段" id="field" v-if="mode !== 'field'">
            <lay-input
                v-model="filedName"
                :allow-clear="true"
                @clear="clearAndGetFields"
                size="sm"
                placeholder="请输入查询，区分大小写"
                @change="queryTargetFields"
                style="width: 80%"
            >
              <template #suffix>
                <lay-icon type="layui-icon-search" @click="queryTargetRules" size="sm"></lay-icon>
              </template>
            </lay-input>
            <lay-scroll :height="'240px'" style="width: 350px">
              <lay-tree
                  :data="fieldsTree"
                  :checkStrictly="true"
                  :showCheckbox="showCheckbox"
                  v-model:checkedKeys="checkedKeysFiled"
                  @node-click="getRuleDetail"
              >
              </lay-tree>
            </lay-scroll>
          </lay-tab-item>
        </lay-tab>
      </lay-row>
      <lay-row space="10" v-if="showCheckbox">
        <lay-col md="6"><span style="margin-top: 10px">插入位置：</span></lay-col>
        <lay-col md="6">
          <lay-input-number
              v-model="tagIndex"
              :step="1" size="sm"
              style="width: 70px"
              :min="1"
              :max="100"
              position="right"></lay-input-number>
        </lay-col>
        <lay-col md="10">
          <lay-button size="sm" type="normal" @click="submitTarget">确定</lay-button>
          <lay-button size="sm" @click="cancelSubmit">取消</lay-button>
        </lay-col>
      </lay-row>
    </lay-card>
</template>

<script lang="ts">
export default {
    name: "RulesTree"
}
</script>

<script lang="ts" setup>
import {onMounted, reactive, ref, watch} from "vue";
import {layer} from "@layui/layui-vue";
import {queryRuleDetailApi, queryTreeRulesApi} from "../../api/module/rule";
import {TreeService} from "../../store/databases/TreeService";
import {TreeNode} from "../../store/databases/TreeNode";
import {notify} from "../../untils/tip";

const rules: any = ref([]);
const checkedKeys = ref([]);

const ruleName = ref('');
const filedName = ref('');

let {showCheckbox, mode} = defineProps({
    showCheckbox: {type: Boolean, default: true},
    mode: {type: String, default: 'scene'},
});

const emitMethod = defineEmits(['insertRule', 'cancelAction']);
let tagIndex: number = 99;

onMounted(()=>{
    getAllRulesTree();
    getFieldsTree();
});

// 获取所有规则树
const getAllRulesTree = async () => {
  let {result, status, message} = await queryTreeRulesApi();
  if(status === 'success'){
    rulesTree.clearTree();
    rules.value = result;
    rulesTree.addRawData(rules.value[0]);
  }else {
    layer.msg(message);
  }
};

// 规则查询
const rulesTree = new TreeService();

const queryTargetRules = () => {
  if(ruleName.value !== ''){
    const tempTree = ref([]);
    rules.value.forEach((unit: TreeNode)=>{
      const newTrees: any = rulesTree.filterTree(unit,
      (node: TreeNode)=>{return node.title.includes(ruleName.value);})
      if(newTrees){
        newTrees.spread = true;
        tempTree.value.push(newTrees);
      }
    })
    rules.value = tempTree.value;
  }else {
    getAllRulesTree();
  }
};

const clearAndGetRules = () => {
  getAllRulesTree();
};

const getRuleDetail = (node: any) => {
  if(!showCheckbox && node.children.length === 0){
    console.log(node)
    emitMethod('insertRule', node.id)
  }
};

const cancelSubmit = () => {
    emitMethod('cancelAction')
};


// ------------------- 依赖字段 ----------
const dependType = ref('rule');

const treeServiceTwo = new TreeService();
const fieldsTree: any = ref([]);
const checkedKeysFiled = ref([]);

const clearAndGetFields = () => {
  getFieldsTree();
};

const queryTargetFields = () => {
  if(filedName.value !== ''){
    const tempTree = ref([]);
    fieldsTree.value.forEach((unit: TreeNode)=>{
      const newTrees: any = treeServiceTwo.filterTree(unit,
      (node: TreeNode)=>{return node.title.includes(filedName.value);})
      if(newTrees){
        newTrees.spread = true;
        tempTree.value.push(newTrees);
      }
    })
    fieldsTree.value = tempTree.value;
  }else {
    getFieldsTree();
  }
};


const getFieldsTree = () => {
  const scene_depend_tables: any = localStorage.getItem('scene_depend_tables');
  console.log("scene_depend_tables:", scene_depend_tables)
  if(scene_depend_tables){
    treeServiceTwo.clearTree();
    fieldsTree.value = JSON.parse(scene_depend_tables);
    console.log("fieldsTree:", fieldsTree.value);
    treeServiceTwo.addRawData(fieldsTree.value[0]);
  }
}

const submitTarget = () => {
  if(dependType.value === 'rule') {
    const lg = checkedKeys.value.length;
    checkedKeys.value.forEach(async (unit, index) => {
      const {status, result, message} = await queryRuleDetailApi({function_id: unit});
      console.log('response result:', result)
      console.log('response.status:', status)
      if (status === 'success') {
        console.log('submitTarget:', tagIndex, result)
        emitMethod('insertRule', tagIndex-1, result);
        tagIndex += 1;
      }else {
        notify(status, message);
      }
      if(index === lg-1){
        emitMethod('cancelAction');
      }
    })
  }else {
    const targetNodes: any = treeServiceTwo.fundTargetTables(checkedKeysFiled.value, "db_field");
    console.log('checkedKeysFiled', checkedKeysFiled.value)
    targetNodes.forEach((targetNode: TreeNode)=>{
      console.log('checkedKeysFiled:', targetNode)
      // const field_name = targetNode?.database + "." + targetNode?.table + "." + targetNode?.title;
      const relationField = reactive({
        object: 'field',
        id: targetNode?.id,
        database: targetNode?.database,
        table: targetNode?.table,
        db_id: targetNode?.db_id,
        field: targetNode?.field
      })
      emitMethod('insertRule', tagIndex-1, relationField);
    })
  }
}
</script>

<style scoped>

</style>